package org.jeecg.qis.controller;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.basic.entity.MesLineStnCfg;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.qis.entity.MesProcDataCfg;
import org.jeecg.qis.service.IMesProcDataCfgService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * @Description: 设备检验参数配置
 * @Author: LiCY
 * @Date:   2023-06-19
 * @Version: V1.0
 */
@Api(tags="设备检验参数配置")
@RestController
@RequestMapping("/qis/mesProcDataCfg")
@Slf4j
public class MesProcDataCfgController extends JeecgController<MesProcDataCfg, IMesProcDataCfgService> {
	@Autowired
	private IMesProcDataCfgService mesProcDataCfgService;

	@Resource
	private CommonAPI sysBaseApiImpl;
	
	/**
	 * 分页列表查询666
	 *
	 * @param mesProcDataCfg
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "设备检验参数配置-分页列表查询")
	@ApiOperation(value="设备检验参数配置-分页列表查询", notes="设备检验参数配置-分页列表查询")
	@GetMapping(value = "/list")
	@DS("#header.his")
	public Result<IPage<MesProcDataCfg>> queryPageList(MesProcDataCfg mesProcDataCfg,
													   String partNo,
													   String pnGroup,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<MesProcDataCfg> queryWrapper = QueryGenerator.initQueryWrapper(mesProcDataCfg, req.getParameterMap());
		queryWrapper.in("partno",partNo,pnGroup);
		Page<MesProcDataCfg> page = new Page<MesProcDataCfg>(pageNo, pageSize);
		IPage<MesProcDataCfg> pageList = mesProcDataCfgService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param mesProcDataCfg
	 * @return
	 */
	@AutoLog(value = "设备检验参数配置-添加")
	@ApiOperation(value="设备检验参数配置-添加", notes="设备检验参数配置-添加")
	//@RequiresPermissions("org.jeecg.modules.demo:mes_proc_data_cfg:add")
	@PostMapping(value = "/add")
	@DS("#header.line")
	public Result<String> add(@RequestBody MesProcDataCfg mesProcDataCfg) {
		return mesProcDataCfgService.insertCfg(mesProcDataCfg);
	}
	
	/**
	 *  编辑
	 *
	 * @param mesProcDataCfg
	 * @return
	 */
	@AutoLog(value = "设备检验参数配置-编辑")
	@ApiOperation(value="设备检验参数配置-编辑", notes="设备检验参数配置-编辑")
	//@RequiresPermissions("org.jeecg.modules.demo:mes_proc_data_cfg:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	@DS("#header.line")
	public Result<String> edit(@RequestBody MesProcDataCfg mesProcDataCfg) {
		mesProcDataCfgService.updateById(mesProcDataCfg);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过选中对象删除
	 *
	 * @param mesProcDataCfg
	 * @return
	 */
	@AutoLog(value = "设备检验参数配置-通过id删除")
	@ApiOperation(value="设备检验参数配置-通过id删除", notes="设备检验参数配置-通过id删除")
	//@RequiresPermissions("org.jeecg.modules.demo:mes_proc_data_cfg:delete")
	@RequestMapping(value = "/delete")
	public Result<String> delete(@RequestBody MesProcDataCfg mesProcDataCfg) {
		mesProcDataCfgService.removeById(mesProcDataCfg);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param list
	 * @return
	 */
	@AutoLog(value = "设备检验参数配置-批量删除")
	@ApiOperation(value="设备检验参数配置-批量删除", notes="设备检验参数配置-批量删除")
	//@RequiresPermissions("org.jeecg.modules.demo:mes_proc_data_cfg:deleteBatch")
	@RequestMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestBody List<MesProcDataCfg> list) {
	    list.forEach(item->{
    			mesProcDataCfgService.removeById(item);
    		});
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "设备检验参数配置-通过id查询")
	@ApiOperation(value="设备检验参数配置-通过id查询", notes="设备检验参数配置-通过id查询")
	@GetMapping(value = "/queryById")
	@DS("#header.his")
	public Result<MesProcDataCfg> queryById(@RequestParam(name="id",required=true) String id) {
		MesProcDataCfg mesProcDataCfg = mesProcDataCfgService.getById(id);
		if(mesProcDataCfg==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(mesProcDataCfg);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param mesProcDataCfg
    */
    //@RequiresPermissions("org.jeecg.modules.demo:mes_proc_data_cfg:exportXls")
    @RequestMapping(value = "/exportXls")
    @DS("#header.his")
    public ModelAndView exportXls(HttpServletRequest request, MesProcDataCfg mesProcDataCfg) {
		String partNo = request.getParameter("partNo");
//		if (StringUtils.isNotBlank(partNo)) {
//			mesProcDataCfg.setPartno(partNo);
//		}
		String title = "设备检验参数配置";
		// Step.1 组装查询条件
		//QueryWrapper<MesProcDataCfg> queryWrapper = new QueryWrapper<>();
		QueryWrapper<MesProcDataCfg> queryWrapper = QueryGenerator.initQueryWrapper(mesProcDataCfg, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String pnGroup = request.getParameter("pnGroup");
		if (StringUtils.isNotBlank(pnGroup)) {
			queryWrapper.in("partno",partNo,pnGroup);
		}else {
			queryWrapper.eq("partno",partNo);
		}
		// Step.2 获取导出数据
		List<MesProcDataCfg> exportList = service.list(queryWrapper);

		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		//此处设置的filename无效 ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.FILE_NAME, title);
		mv.addObject(NormalExcelConstants.CLASS, MesProcDataCfg.class);
		//update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
		ExportParams exportParams = new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
		//update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
		mv.addObject(NormalExcelConstants.PARAMS, exportParams);
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("mes_proc_data_cfg:importExcel")
    @DS("#header.line")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<MesProcDataCfg> list = ExcelImportUtil.importExcel(file.getInputStream(), MesProcDataCfg.class, params);
				System.out.println(MesProcDataCfg.class.getSimpleName());
				//update-begin-author:taoyan date:20190528 for:批量插入数据
				long start = System.currentTimeMillis();
				list.forEach(item -> {
//					item.setRecId()
					String line = item.getLine();
					String op = item.getOp();
					String partNo = item.getPartno();
					String addr = item.getAddress();
					String serialNumber = "";
					serialNumber = sysBaseApiImpl.getProcSerialNumber(addr);
					String recId = sysBaseApiImpl.getPrefix(line,op,partNo) + serialNumber;
					item.setRecId(recId);
					item.setCtime(new Date());
					if (item.getStatus().equalsIgnoreCase("enabled")) {
						item.setStatus("1");
					} else if (item.getStatus().equalsIgnoreCase("disabled")) {
						item.setStatus("0");
					} else {
						item.setStatus("1");
					}
					if (item.getLimitCheck().equalsIgnoreCase("uncheck")) {
						item.setLimitCheck("0");
					} else if (item.getLimitCheck().equalsIgnoreCase("check")) {
						item.setLimitCheck("1");
					} else if (item.getLimitCheck().equalsIgnoreCase("checkresult")) {
						item.setLimitCheck("2");
					} else if (item.getLimitCheck().equalsIgnoreCase("checkspc")){
						item.setLimitCheck("3");
					} else {
						item.setLimitCheck("0");
					}
					mesProcDataCfgService.save(item);
				});
				//service.saveBatch(list);
				//400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
				//1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				//update-end-author:taoyan date:20190528 for:批量插入数据
				return Result.ok("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				String msg = e.getMessage();
				log.error(msg, e);
				if (msg != null && msg.indexOf("Duplicate entry") >= 0) {
					return Result.error("文件导入失败:有重复数据！");
				} else {
					return Result.error("文件导入失败:" + e.getMessage());
				}
				//update-end-author:taoyan date:20211124 for: 导入数据重复增加提示
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
    }



	 /**
	  * 通过op查询
	  *
	  * @param partno
	  * @return
	  */
	 //@AutoLog(value = "工位配置-通过op查询")
	 @ApiOperation(value = "通过产品编号查询参数配置", notes = "通过产品编号查询参数配置")
	 @GetMapping(value = "/procSelect")
	 @DS("#header.his")
	 public Result<List<MesProcDataCfg>> procSelect(@RequestParam(name = "partno", required = true) String partno) {
		 HashMap<String, Object> map = new HashMap<>();
//        map.put("line", line);
		 map.put("partno", partno);
		 List<MesProcDataCfg> procSelects = mesProcDataCfgService.listByMap(map);
		 if (procSelects.isEmpty()) {
			 return Result.error("未找到对应数据");
		 }
		 return Result.OK(procSelects);
	 }

}
